package com.ling.tools.login.config;


import com.ling.tools.login.entity.User;
import com.ling.tools.login.mapper.UserDao;
import com.ling.tools.login.utils.PwdUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * File Name: MyRealm
 * Date: 2020/2/6 15:27
 * Author: liangling
 * Description
 */
@Component
public class MyRealm extends AuthorizingRealm {


    @Autowired
    private UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        if (null == user) {
            throw new UnknownAccountException("账号不存在");
        }
        return null;
    }

    /**
     * @return
     * @author
     * @Param
     * @Date 2020/2/6 16:57
     * @Des 验证用户名和密码
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //自定义shrio判断用户名和密码逻辑
        //1.判断用户是否存在

        String username = token.getPrincipal() + "";
        User user = userDao.findUserInfoByAccount(username);
        if (null == user) {
            throw new UnknownAccountException("用户不存在");
        }
        //校验用户名密码
//            SimpleAuthenticationInfo simpleAuthenticationInfo =  new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(username),getName());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getAccount(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                getName());
//            //校验通过把用户信息放在session,作为下次访问的身份标识
//            Session session = SecurityUtils.getSubject().getSession();
//            session.setAttribute("userSession",user);
//            session.setAttribute("sessionId",user.getId());


        return authenticationInfo;
    }
}
